package com.hyz.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author HGD
 * @date 2022/10/30 9:04
 */
@Component
public class RedisIdWorker {
    /**
     * 2022/01/01 时间戳
     */
    private static final long BEGIN_TIME = 1640995200L;
    /**
     * 转移位数
     */
    private static final int COUNT_BITS = 32;

    private StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public Long nextId(String keyPrefix) {
        // 1. 生成时间戳
        LocalDateTime time = LocalDateTime.now();
        long nowSecond = time.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIME;

        // 2. 生成序列号
        // 获取当前日期
        String date = time.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));

        // 自增长
        String key = "icr:" + keyPrefix + date;
        long delTime = 10L;
        long count = stringRedisTemplate.opsForValue().increment(key);
        // 3. 拼接
        return timestamp << COUNT_BITS | count;
    }
}
